package com.xiaoyu.client.ui.activity.mall;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.NestedScrollView;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.xiaoyu.client.ClientConstants;
import com.xiaoyu.client.R;
import com.xiaoyu.client.model.store.StoreDetailBean;
import com.xiaoyu.client.network.NetworkManager;
import com.xiaoyu.client.ui.fragment.mall.store.StoreCommentsFragment;
import com.xiaoyu.client.ui.fragment.mall.store.StoreIntroductionFragment;
import com.xiaoyu.client.ui.fragment.mall.store.StoreProductFragment;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.ui.base.BaseActivity;
import com.xiaoyu.commonlib.ui.widget.AutofitHeightViewPager;
import com.xiaoyu.commonlib.utils.CCircleImageView;
import com.xiaoyu.commonlib.utils.CommonFragmentPagerAdapter;
import com.xiaoyu.commonlib.utils.ToastUtil;
import com.xiaoyu.commonlib.utils.UIUtils;
import com.xiaoyu.commonlib.utils.ViewPagerUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 商铺详情页
 * Created by jk 2018/11/27
 */
public class StoreActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.activity_store_background_img)
    ImageView backgroundImg;//顶部背景
    @BindView(R.id.activity_store_img)
    CCircleImageView storeImg;//头像
    @BindView(R.id.activity_store_name)
    TextView storeName;//昵称
    @BindView(R.id.activity_store_score)
    TextView storeScore;//评分
    @BindView(R.id.activity_store_sales)
    TextView storeSales;//销量
    @BindView(R.id.activity_store_score_sales)
    LinearLayout mScoreSales;
    @BindView(R.id.activity_store_function_layout)
    LinearLayout functionLayout;//导航栏
    @BindView(R.id.activity_store_line)
    View mLine;//导航栏标示线
    @BindView(R.id.activity_store_view_page)
    public AutofitHeightViewPager mViewPager;
    @BindView(R.id.activity_store_scroll_view)
    NestedScrollView mScrollView;//滚动控件
    @BindView(R.id.top_title_bar)
    RelativeLayout mTitleBar;//顶部导航栏

    private ViewPagerUtils pagerUtils;
    private CommonFragmentPagerAdapter mPagerAdapter;
    private List<Fragment> mFragmentList = new ArrayList<>();
    private String storeId;//商家id
    private float maxHeight;//最大滚动高度

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_store);
        ButterKnife.bind(this);
        storeId = getIntent().getStringExtra(ClientConstants.STORE_ID);
        initView();
        getStoreInfo();
    }

    private void initView() {
        //商家背景
        backgroundImg.setFocusable(true);
        backgroundImg.setFocusableInTouchMode(true);
        backgroundImg.requestFocus();
        //中部功能导航栏
        pagerUtils = new ViewPagerUtils(this, functionLayout, mLine);
        pagerUtils.initLine(UIUtils.dip2px(50));
        pagerUtils.setTextColor("#333333", "#1772e5");
        pagerUtils.selectItem(0);

        for (int i = 0; i < functionLayout.getChildCount(); i++) {
            functionLayout.getChildAt(i).setOnClickListener(this);
        }

        //ViewPager
        mPagerAdapter = new CommonFragmentPagerAdapter(getSupportFragmentManager(), mFragmentList);
        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.addOnPageChangeListener(onPageChangeListener);
        mViewPager.setCurrentItem(2);

        //ScrollView和titleBar
        mTitleBar.getBackground().setAlpha(0);
        mScrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                maxHeight = backgroundImg.getHeight();
                mScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
                    @Override
                    public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                        if (scrollY <= 0){
                            mTitleBar.getBackground().setAlpha(0);
                        }else if (scrollY < maxHeight){
                            float scale = scrollY / maxHeight;
                            mTitleBar.getBackground().setAlpha((int) (scale*255));
                        }else {
                            mTitleBar.getBackground().setAlpha(255);
                        }
                    }
                });
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v == functionLayout.getChildAt(0)) {//产品
            pagerUtils.scrollLineMove(0, 0);
            pagerUtils.selectItem(0);
            mViewPager.setCurrentItem(0);
            mViewPager.updateHeight(0);
        } else if (v == functionLayout.getChildAt(1)) {//评价
            pagerUtils.scrollLineMove(1, 0);
            pagerUtils.selectItem(1);
            mViewPager.setCurrentItem(1);
            mViewPager.updateHeight(1);
        } else if (v == functionLayout.getChildAt(2)) {//商家
            pagerUtils.scrollLineMove(2, 0);
            pagerUtils.selectItem(2);
            mViewPager.setCurrentItem(2);
            mViewPager.updateHeight(2);
        }
    }

    //返回
    @OnClick(R.id.activity_store_title_back_btn)
    public void backClick() {
        onBackPressed();
    }



    /**
     * ViewPager滑动监听
     */
    private ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            pagerUtils.scrollLineMove(position, positionOffset);
        }

        @Override
        public void onPageSelected(int position) {
            mViewPager.updateHeight(position);
            pagerUtils.scrollLineMove(position,0);
            pagerUtils.selectItem(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    private void getStoreInfo() {
        NetworkManager.getStoreDetailInfo(storeId, new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                parseStoreInfoSuc(result);
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
                ToastUtil.logError("商家详情", errorCode, errorDiscription);
            }
        });
    }

    private void parseStoreInfoSuc(String result) {
        ToastUtil.logResult("商家详情", result);
        StoreDetailBean bean = new Gson().fromJson(result, StoreDetailBean.class);
        Glide.with(this).load(bean.getData().getStoreackground()).into(backgroundImg);//顶部背景
        Glide.with(this).load(bean.getData().getStoreimg()).into(storeImg);//商家头像
        storeName.setText(bean.getData().getStorename());//商家名称
        storeScore.setText("评分：" + bean.getData().getAvg());//评分
        storeSales.setText("销量：" + bean.getData().getStoresales());//销量

        initFragment(bean.getData());
    }

    private void initFragment(StoreDetailBean.DataBean data) {
        StoreProductFragment productFragment = new StoreProductFragment();
        Bundle pBundle = new Bundle();
        pBundle.putString(ClientConstants.STORE_ID, storeId);
        pBundle.putSerializable(ClientConstants.MERCHANT_INFO, data);
        pBundle.putInt(AutofitHeightViewPager.POSITION, 0);
        productFragment.setArguments(pBundle);
        StoreCommentsFragment commentsFragment = new StoreCommentsFragment();
        Bundle cBundle = new Bundle();
        cBundle.putSerializable(ClientConstants.MERCHANT_INFO, data);
        cBundle.putInt(AutofitHeightViewPager.POSITION, 1);
        commentsFragment.setArguments(cBundle);
        StoreIntroductionFragment introductionFragment = new StoreIntroductionFragment();
        Bundle iBundle = new Bundle();
        iBundle.putSerializable(ClientConstants.MERCHANT_INFO, data);
        iBundle.putInt(AutofitHeightViewPager.POSITION, 2);
        introductionFragment.setArguments(iBundle);
        mFragmentList.clear();
        mFragmentList.add(productFragment);
        mFragmentList.add(commentsFragment);
        mFragmentList.add(introductionFragment);
        mPagerAdapter.updateList(mFragmentList);
    }
}
